/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.web.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.monitor.utils.Achieve;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.mapper.UserMapper;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.web.entity.WxAgents;
import com.jeeplus.modules.web.entity.WxAgentsRecording;
import com.jeeplus.modules.web.mapper.WxAgentsMapper;
import com.jeeplus.modules.web.mapper.WxAgentsRecordingMapper;
import com.jeeplus.modules.web.service.WxAgentsRecordingService;

/**
 * 分销商收入记录Controller
 *
 * @author rongjie
 * @version 2017-09-02
 */
@Controller
@RequestMapping(value = "${adminPath}/web/wxAgentsRecording")
public class WxAgentsRecordingController extends BaseController {

	@Autowired
	private WxAgentsRecordingService wxAgentsRecordingService;
	@Autowired
	private WxAgentsRecordingMapper wxAgentsRecordingMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private WxAgentsMapper wxAgentsMapper;
	private static final Logger log = LoggerFactory.getLogger(WxAgentsRecordingController.class);

	@ModelAttribute
	public WxAgentsRecording get(@RequestParam(required = false) String id) {
		WxAgentsRecording entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = wxAgentsRecordingService.get(id);
		}
		if (entity == null) {
			entity = new WxAgentsRecording();
		}
		return entity;
	}

	/**
	 * 代理商分销收益明细界面
	 */
	@RequiresPermissions("web:wxAgentsRecording:list")
	@RequestMapping(value = { "list", "" })
	public String list(Model model) {

		// List<Map<String, Object>> list = userMapper.getShopTotal();
		WxAgents wxAgents = new WxAgents();
		wxAgents.setStatus(1);
		User currentUser = UserUtils.getUser();
		WxAgents currentAgents = null;
		List<WxAgents> list = null;
		if (!currentUser.getId().equals("1")) {// 不是管理员，权限过滤
			currentAgents = wxAgentsMapper.findUniqueByProperty("username", currentUser.getMobile());
			Map<String, List<WxAgents>> listmap = recursionAgents(Integer.parseInt(currentAgents.getId()));
			model.addAttribute("childList", listmap.get("childList"));
			model.addAttribute("shopList", listmap.get("shopList"));
		} else {
			wxAgents.setAgentLevel(0);
			list = wxAgentsMapper.selectList(wxAgents);
			model.addAttribute("list", list);
		}
		model.addAttribute("currentAgents", currentAgents);

		return "modules/web/wxAgentsRecordingList";
	}

	/**
	 * 分销商收入记录列表数据
	 */
	@ResponseBody
	@RequiresPermissions("web:wxAgentsRecording:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(WxAgentsRecording wxAgentsRecording, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		// 非管理员账户，能查看自己或下层代理的分销记录
		if (!currentUser.getId().equals("1") && wxAgentsRecording.getAgents() == null) {
			WxAgents wxAgents = wxAgentsMapper.findUniqueByProperty("username", currentUser.getMobile());
			// wxAgents.setUserName(currentUser.getMobile());
			wxAgentsRecording.setAgents(wxAgents);

		}
		Page<WxAgentsRecording> page = wxAgentsRecordingService.findPage(new Page<WxAgentsRecording>(request, response),
				wxAgentsRecording);

		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑分销商收入记录表单页面
	 */
	@RequiresPermissions(value = { "web:wxAgentsRecording:view", "web:wxAgentsRecording:add",
			"web:wxAgentsRecording:edit" }, logical = Logical.OR)
	@RequestMapping(value = "form")
	public String form(WxAgentsRecording wxAgentsRecording, Model model) {
		model.addAttribute("wxAgentsRecording", wxAgentsRecording);
		if (StringUtils.isBlank(wxAgentsRecording.getId())) {// 如果ID是空为添加
			model.addAttribute("isAdd", true);
		}
		return "modules/web/wxAgentsRecordingForm";
	}

	/**
	 * 保存分销商收入记录
	 */
	@RequiresPermissions(value = { "web:wxAgentsRecording:add", "web:wxAgentsRecording:edit" }, logical = Logical.OR)
	@RequestMapping(value = "save")
	public String save(WxAgentsRecording wxAgentsRecording, Model model, RedirectAttributes redirectAttributes)
			throws Exception {
		if (!beanValidator(model, wxAgentsRecording)) {
			return form(wxAgentsRecording, model);
		}
		// 新增或编辑表单保存
		wxAgentsRecordingService.save(wxAgentsRecording);// 保存
		addMessage(redirectAttributes, "保存分销商收入记录成功");
		return "redirect:" + Global.getAdminPath() + "/web/wxAgentsRecording/?repage";
	}

	/**
	 * 删除分销商收入记录
	 */
	@ResponseBody
	@RequiresPermissions("web:wxAgentsRecording:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(WxAgentsRecording wxAgentsRecording, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		wxAgentsRecordingService.delete(wxAgentsRecording);
		j.setMsg("删除分销商收入记录成功");
		return j;
	}

	/**
	 * 删除分销商收入记录
	 */
	@ResponseBody
	@RequestMapping(value = "getUser")
	public AjaxJson getUser(String cId, WxAgentsRecording wxAgentsRecording, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		LinkedHashMap map = new LinkedHashMap();
		List<Map<String, Object>> mapList = new ArrayList<>();
		map.put("type", userMapper.getTypeUser(cId, "fbe7c20468d44b9da9b4a23207a038b2"));
		map.put("type1", userMapper.getTypeUser(cId, "f6c42e28c02f45b0a79c0159dcc3caad"));
		j.setMsg("查询成功");
		j.setBody(map);
		return j;
	}

	/**
	 * 获取下级分销商
	 */
	@SuppressWarnings("unlikely-arg-type")
	@ResponseBody
	@RequestMapping(value = "selectChilds")
	public AjaxJson selectChilds(Integer parentId) {

		Map<String, List<WxAgents>> listmap = recursionAgents(parentId);
		AjaxJson j = new AjaxJson();
		LinkedHashMap<String, Object> map = new LinkedHashMap<>();
		map.put("childList", listmap.get("childList"));
		map.put("shopList", listmap.get("shopList"));
		j.setMsg("查询成功");
		j.setBody(map);
		return j;
	}

	private Map<String, List<WxAgents>> recursionAgents(Integer parentId) {
		WxAgents wxAgents = new WxAgents();
		wxAgents.setParentId(parentId);
		wxAgents.setStatus(1);

		List<WxAgents> childList = wxAgentsMapper.selectList(wxAgents);
		List<WxAgents> shopList = new ArrayList<WxAgents>();

		for (Iterator<WxAgents> iterator = childList.iterator(); iterator.hasNext();) {
			WxAgents elem = (WxAgents) iterator.next();
			if (elem.getAgentLevel() == 3) {
				shopList.add(elem);
				iterator.remove();
			} else if (elem.getId().equals(String.valueOf(parentId))) {
				iterator.remove();
			}
		}
		HashMap<String, List<WxAgents>> hashMap = new HashMap<>();
		hashMap.put("childList", childList);
		hashMap.put("shopList", shopList);
		return hashMap;

	}

	/**
	 * 删除分销商收入记录
	 */
	@ResponseBody
	@RequestMapping(value = "getUsers")
	public AjaxJson getUsers(String cId, WxAgentsRecording wxAgentsRecording, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		LinkedHashMap map = new LinkedHashMap();
		List<Map<String, Object>> mapList = new ArrayList<>();
		map.put("type", userMapper.getTypeUser(cId, "f6c42e28c02f45b0a79c0159dcc3caad"));
		j.setMsg("查询成功");
		j.setBody(map);
		return j;
	}

	/**
	 * 批量删除分销商收入记录
	 */
	@ResponseBody
	@RequiresPermissions("web:wxAgentsRecording:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] = ids.split(",");
		for (String id : idArray) {
			wxAgentsRecordingService.delete(wxAgentsRecordingService.get(id));
		}
		j.setMsg("删除分销商收入记录成功");
		return j;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("web:wxAgentsRecording:export")
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public AjaxJson exportFile(WxAgentsRecording wxAgentsRecording, HttpServletRequest request,
			HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "分销商收入记录" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Page<WxAgentsRecording> page = wxAgentsRecordingService
					.findPage(new Page<WxAgentsRecording>(request, response, -1), wxAgentsRecording);
			new ExportExcel("分销商收入记录", WxAgentsRecording.class).setDataList(page.getList()).write(response, fileName)
					.dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出分销商收入记录记录失败！失败信息：" + e.getMessage());
		}
		return j;
	}

	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式

	/**
	 * 金额
	 */
	@ResponseBody
	@RequestMapping(value = "getMoney")
	public AjaxJson getMoney(String time, String endTime, WxAgentsRecording wxAgentsRecording,
			HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		wxAgentsRecording.setTimeEnd(df.format(Long.valueOf(endTime)));
		wxAgentsRecording.setSetTime(df.format(Long.valueOf(time)));

		// 收益汇总
		WxAgentsRecording listMoney = wxAgentsRecordingMapper.findListMoney(wxAgentsRecording);
		// 订单金额汇总
		//Double s2 = wxAgentsRecordingMapper.findRecordingOrderMoneyList(wxAgentsRecording);

		LinkedHashMap<String, Object> map = new LinkedHashMap<>();
		if (listMoney == null) {
			map.put("s1", 0D);
			map.put("s2", 0D);
		} else {
			map.put("s1", listMoney.getMoney());
			map.put("s2", listMoney.getOrderMoney());
		}

		logger.debug(map.toString());
		j.setMsg("查询成功");
		j.setBody(map);
		return j;
	}

	/**
	 * 导入Excel数据
	 *
	 */
	@RequiresPermissions("web:wxAgentsRecording:import")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WxAgentsRecording> list = ei.getDataList(WxAgentsRecording.class);
			for (WxAgentsRecording wxAgentsRecording : list) {
				try {
					wxAgentsRecordingService.save(wxAgentsRecording);
					successNum++;
				} catch (ConstraintViolationException ex) {
					failureNum++;
				} catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条分销商收入记录记录。");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条分销商收入记录记录" + failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入分销商收入记录失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/web/wxAgentsRecording/?repage";
	}

	/**
	 * 下载导入分销商收入记录数据模板
	 */
	@RequiresPermissions("web:wxAgentsRecording:import")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "分销商收入记录数据导入模板.xlsx";
			List<WxAgentsRecording> list = Lists.newArrayList();
			new ExportExcel("分销商收入记录数据", WxAgentsRecording.class, 1).setDataList(list).write(response, fileName)
					.dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/web/wxAgentsRecording/?repage";
	}

}
